﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Neits.PersistenceService;
using Microsoft.Practices.Unity;
using Neits.Common;
using Neits.UserService;

namespace Projecturo.Connectivity
{
    public class Storage : IStorage
    {
        [Dependency]
        public IPersistenceService PersistenceService { get; set; }

        #region IStorage Member

        public void Delete(object entity)
        {
            PersistenceService.Delete(entity);
        }

        public T Get<T>(long id)
        {
            return PersistenceService.Get<T>(id);
        }

        public IList<T> GetList<T>()
        {
            return PersistenceService.GetList<T>();
        }

        public IList<T> GetList<T>(Filter filter)
        {
            return PersistenceService.GetList<T>(filter);
        }

        public void Refresh(object entity)
        {
            PersistenceService.Refresh(entity);
        }

        public void Save(object entity)
        {
            IInstanceIdentifier instanceIdentifier = entity as IInstanceIdentifier;
            if (instanceIdentifier != null)
            {
                if (entity is ICreated && instanceIdentifier.Id < 1)
                {
                    ((ICreated)entity).CreateDate = DateTime.Now;
                    ((ICreated)entity).CreatedBy = System.Threading.Thread.CurrentPrincipal as IUser;
                }
                if (entity is IChanged)
                {
                    ((IChanged)entity).ChangeDate = DateTime.Now;
                    ((IChanged)entity).ChangedBy = System.Threading.Thread.CurrentPrincipal as IUser;
                }
                if (entity is IHasDataContext)
                {
                    ((IHasDataContext)entity).DataContext = (System.Threading.Thread.CurrentPrincipal as IUser).DataContext;
                }
            }
            PersistenceService.Save(entity);
        }

        #endregion
    }
}
